<template>
  <div class="home">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">众筹平台</h1>
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">首页</el-menu-item>
            <el-menu-item index="/campaigns">众筹列表</el-menu-item>
            <el-menu-item index="/create">创建众筹</el-menu-item>
            <el-menu-item index="/my-campaigns">我的众筹</el-menu-item>
          </el-menu>
          <div class="user-info">
            <el-button
              v-if="!walletConnected"
              type="primary"
              size="small"
              @click="connectWallet"
            >
              连接钱包
            </el-button>
            <span v-else class="wallet-address">{{ shortAddress }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <div class="welcome-section">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <h2>欢迎，{{ user.username }}！</h2>
            </div>
            
            <div class="user-details">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="用户名">
                  {{ user.username }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                  {{ user.email || '未设置' }}
                </el-descriptions-item>
                <el-descriptions-item label="钱包地址 (EOA)">
                  <div class="wallet-info">
                    <span v-if="walletAddress">{{ walletAddress }}</span>
                    <span v-else class="not-connected">未连接</span>
                    <el-button
                      v-if="walletConnected && !user.walletAddress"
                      type="text"
                      size="small"
                      @click="bindWallet"
                    >
                      绑定钱包
                    </el-button>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="钱包余额" v-if="walletConnected">
                  {{ balance }} ETH
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">
                  {{ formatDate(user.createdAt) }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>

          <div class="stats-header">
            <h3>数据统计</h3>
            <el-button
              v-if="walletConnected"
              type="text"
              icon="el-icon-refresh"
              :loading="loadingStats"
              @click="loadUserStats"
              size="small"
            >
              刷新
            </el-button>
          </div>

          <el-row :gutter="20" class="stats-section">
            <el-col :span="8">
              <el-card class="stat-card" @click.native="$router.push('/my-campaigns')">
                <div class="stat-content" v-loading="loadingStats && walletConnected">
                  <i class="el-icon-document stat-icon"></i>
                  <div class="stat-text">
                    <div class="stat-label">我创建的众筹</div>
                    <div class="stat-value">{{ walletConnected ? stats.created : '-' }}</div>
                    <div class="stat-hint" v-if="!walletConnected">需要连接钱包</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card" @click.native="$router.push('/my-campaigns?tab=backed')">
                <div class="stat-content" v-loading="loadingStats && walletConnected">
                  <i class="el-icon-star-on stat-icon"></i>
                  <div class="stat-text">
                    <div class="stat-label">我支持的众筹</div>
                    <div class="stat-value">{{ walletConnected ? stats.backed : '-' }}</div>
                    <div class="stat-hint" v-if="!walletConnected">需要连接钱包</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card" @click.native="$router.push('/campaigns')">
                <div class="stat-content" v-loading="!walletConnected && stats.total === 0">
                  <i class="el-icon-trophy stat-icon"></i>
                  <div class="stat-text">
                    <div class="stat-label">平台总众筹</div>
                    <div class="stat-value">{{ stats.total }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <div class="quick-actions">
            <h3>快速操作</h3>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-button type="primary" icon="el-icon-plus" @click="$router.push('/create')">
                  创建众筹
                </el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="success" icon="el-icon-search" @click="$router.push('/campaigns')">
                  浏览众筹
                </el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="info" icon="el-icon-folder" @click="$router.push('/my-campaigns')">
                  我的众筹
                </el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import userApi from '@/api/user';
import contractService from '@/api/contract';

export default {
  name: 'Home',
  data() {
    return {
      user: {},
      walletAddress: '',
      walletConnected: false,
      balance: '0.00',
      stats: {
        created: 0,
        backed: 0,
        total: 0
      },
      activeMenu: '/home',
      loadingStats: false
    };
  },
  computed: {
    shortAddress() {
      if (!this.walletAddress) return '';
      return `${this.walletAddress.substring(0, 6)}...${this.walletAddress.substring(38)}`;
    }
  },
  created() {
    this.loadUserInfo();
    this.activeMenu = this.$route.path;
    // 尝试加载总众筹数量（不需要钱包连接）
    this.loadTotalCampaigns();
    // 检查钱包连接状态
    this.checkWalletConnection();
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    },
    
    async checkWalletConnection() {
      // 优先从 localStorage 恢复（快速显示，避免刷新后闪烁）
      const savedAddress = localStorage.getItem('walletAddress');
      if (savedAddress) {
        this.walletAddress = savedAddress;
        this.walletConnected = true;
        console.log('从 localStorage 恢复钱包地址:', savedAddress);
      }
      
      // 检查 web3Helper 中是否已有账户（可能在其他页面已连接）
      const account = web3Helper.getAccount();
      
      // 如果还没有账户，等待一下异步检查完成
      if (!account && savedAddress) {
        // 等待最多 1 秒让 checkExistingConnection 完成
        for (let i = 0; i < 10; i++) {
          await new Promise(resolve => setTimeout(resolve, 100));
          const currentAccount = web3Helper.getAccount();
          if (currentAccount) {
            break;
          }
        }
      }
      
      const finalAccount = web3Helper.getAccount();
      if (finalAccount) {
        this.walletAddress = finalAccount;
        this.walletConnected = true;
        
        // 获取余额
        try {
          const balance = await web3Helper.getBalance(finalAccount);
          this.balance = parseFloat(balance).toFixed(4);
        } catch (error) {
          console.error('获取余额失败:', error);
        }
        
        // 加载统计数据
        await this.loadUserStats();
      } else if (savedAddress) {
        // localStorage 有地址但 web3Helper 没有，说明用户可能断开了 MetaMask
        // 清除状态
        this.walletConnected = false;
        this.walletAddress = '';
        localStorage.removeItem('walletAddress');
      }
    },
    
    async loadTotalCampaigns() {
      try {
        // 只读模式：不需要连接钱包
        await contractService.init(true);
        const total = await contractService.getCampaignCount();
        this.stats.total = total;
      } catch (error) {
        console.error('加载总众筹数量失败:', error);
        // 不显示错误提示，避免影响用户体验
      }
    },
    
    async loadUserStats() {
      if (!this.walletAddress) return;
      
      this.loadingStats = true;
      try {
        // 写入模式：需要连接钱包（此时用户已连接）
        await contractService.init(false);
        
        // 获取用户创建的众筹
        const createdIds = await contractService.getUserCreatedCampaigns(this.walletAddress);
        this.stats.created = createdIds.length;
        
        // 获取用户支持的众筹
        const backedIds = await contractService.getUserBackedCampaigns(this.walletAddress);
        this.stats.backed = backedIds.length;
        
        // 获取总众筹数量
        const total = await contractService.getCampaignCount();
        this.stats.total = total;
        
        console.log('统计数据加载成功:', this.stats);
      } catch (error) {
        console.error('加载统计数据失败:', error);
        this.$message.warning('统计数据加载失败，请稍后重试');
      } finally {
        this.loadingStats = false;
      }
    },
    
    async connectWallet() {
      try {
        const address = await web3Helper.connect();
        this.walletAddress = address;
        this.walletConnected = true;
        
        // 获取余额
        const balance = await web3Helper.getBalance(address);
        this.balance = parseFloat(balance).toFixed(4);
        
        this.$message.success('钱包连接成功！');
        
        // 加载用户统计数据
        await this.loadUserStats();
        
        // 提示用户绑定钱包
        if (!this.user.walletAddress) {
          this.$confirm('是否将此钱包地址绑定到您的账号？', '提示', {
            confirmButtonText: '绑定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            this.bindWallet();
          }).catch(() => {});
        }
      } catch (error) {
        this.$message.error(error.message || '钱包连接失败');
      }
    },
    
    async bindWallet() {
      try {
        const response = await userApi.updateWalletAddress(this.user.id, this.walletAddress);
        if (response.success) {
          this.user.walletAddress = this.walletAddress;
          localStorage.setItem('user', JSON.stringify(this.user));
          this.$message.success('钱包绑定成功！');
        } else {
          this.$message.error(response.message || '绑定失败');
        }
      } catch (error) {
        this.$message.error(error.message || '绑定失败');
      }
    },
    
    handleMenuSelect(index) {
      this.$router.push(index);
    },
    
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user');
        web3Helper.disconnect();
        this.$message.success('已退出登录');
        this.$router.push('/login');
      }).catch(() => {});
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN');
    }
  }
};
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  font-size: 24px;
  color: #409EFF;
  margin: 0;
  margin-right: 40px;
}

.nav-menu {
  flex: 1;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.wallet-address {
  font-family: monospace;
  color: #67C23A;
  font-weight: bold;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.welcome-section {
  max-width: 900px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 30px;
}

.card-header h2 {
  margin: 0;
  color: #333;
}

.user-details {
  padding: 20px 0;
}

.wallet-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.not-connected {
  color: #999;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30px 0 15px 0;
}

.stats-header h3 {
  margin: 0;
  color: #333;
}

.stats-section {
  margin: 15px 0 30px 0;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  min-height: 80px;
}

.stat-icon {
  font-size: 48px;
  color: #409EFF;
}

.stat-text {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

.stat-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.quick-actions {
  margin-top: 30px;
}

.quick-actions h3 {
  margin-bottom: 20px;
  color: #333;
}

.quick-actions .el-button {
  width: 100%;
  height: 60px;
  font-size: 16px;
}
</style>

